// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const CHAT = 'CHAT_LOG'
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  //用户信息主题
  let content = event.content;
  //用户信息类型
  let type = event.type || 'text'
  //用户信息
  let userInfo = event.userInfo;
  //信息发布时间
  let date = event.date;

  let res = await ContentSafe(content)
  console.log(res)
  if(res.result.code == 200){
    //可以写入的数据
    return await db.collection(CHAT).add({
      data:{
        openid,
        userInfo,
        content,
        date,
        type,
        roomid:1
      }
    })
  }else{
    return res.result
  }
}
async function ContentSafe(content){
  //文本内容安全校验
  return await cloud.callFunction({
    name:'openapi',
    data:{
      action:'msgSecCheck',
      content:content
    }
  })
}